import React, { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import "./backbutton.less";

// 只有在这两个 path 下会显示
const pathes = ["/select", "/practice"];

export default function BackButton() {
  const navigate = useNavigate();
  const { pathname } = useLocation();

  const [show, setShow] = useState(false);
  const back = () => {
    navigate(-1);
  };

  useEffect(() => {
    // 取出path里面非动态路由的部分
    const idx = pathname.indexOf("/", 1);
    let temp;
    // 如果有二级路由， idx 就会 > 0
    if (idx > 0) {
      temp = pathname.substring(0, idx);
    } else {
      // 如果没有二级路由，idx会是-1
      temp = pathname;
    }

    setShow(pathes.includes(temp));
  }, [pathname]);

  return (
    <div
      className="back-btn"
      onClick={back}
      style={{ display: show ? "flex" : "none" }}
    >
      返回上一页
    </div>
  );
}
